<?php
namespace app\model;

/**
 * Created by 易宣软件
 * Desc:砍价model
 * User:cbw
 * Date: 2020/12/5
 */
class Bargain{

    /**
     * Desc:获取帮砍有礼列表以及搜素
     * User:cbw
     * Time: 2021/2/23 3:21 下午
     * @param $themeid
     * @param string $search
     * @param string $start_day
     * @param string $end_day
     * @param $page_start
     * @param $page_size
     * @return mixed
     */
    public static function getHelpReceiveFlag($themeid,$search='',$start_day='',$end_day='',$page_start,$page_size,$has_info=2)
    {
        $condition1 = " ";
        $condition = " where a.themeid=$themeid ";
        if ($has_info!=2){
            $condition .= " and a.status=".$has_info;
        }
        if ($search){
            $condition .= " and a.user_name like '".$search."'"." or a.user_mobile like '".$search."' ";
        }
        if ($start_day && $end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        if ($page_size){
            $condition1 = " limit ".$page_start.",".$page_size;
        }
        $sql = "select a.*,b.avatar,b.nickname from ".tablename(t_bargain_help_gift).
            " as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid".$condition.
            " group by a.uid order by a.created_at desc  ".$condition1;
//        var_dump($sql);die();
        return db_select($sql);
    }

    /**
     * Desc:获取用户的帮砍信息
     * User:cbw
     * Time: 2021/3/3 6:57 下午
     * @param $themeid
     * @param $where
     * @return mixed
     */
    public static function getHelpReceiveList($where)
    {
        $res = db_getall(t_bargain_help_gift,$where);
        return $res;
    }

    /**
     * Desc:插入用户帮砍礼品获取记录
     * User:cbw
     * Time: 2021/2/23 3:10 下午
     * @param $data
     * @return bool
     */
    public static function insertHelpReceiveFlag($data)
    {
        $data['updated_at']=date("Y-m-d H:i:s");
        $res = $insertid = db_insert(t_bargain_help_gift,$data);
        if (!$res){
            return false;
        }else{
            return true;
        }
    }

    /**
     * Desc:修改用户帮砍礼品记录
     * User:cbw
     * Time: 2021/2/23 3:09 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editHelpReceiveFlagItem($where,$data)
    {
        $data['updated_at']=date("Y-m-d H:i:s");
        $res = db_update(t_bargain_help_gift,$data,$where);
        return $res;
    }

    /**
     * Desc:获取指定用户的帮砍礼品
     * User:cbw
     * Time: 2021/2/23 7:21 下午
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function getHelpReceiveFlagByUid($uid,$themeid)
    {
        $res = db_get(t_bargain_help_gift,['uid'=>$uid,'themeid'=>$themeid]);
        return $res;
    }

    /**
     * Desc:格式化用户是否存在帮砍礼品
     * User:cbw
     * Time: 2021/2/23 7:25 下午
     * @param $uid
     * @param $themeid
     * @return false[]
     */
    public static function checkUserHasHelpGift($uid,$themeid,$config)
    {
        if (empty($uid)){
            $res = ['has_help_gift'=>0,'title'=>'','img'=>'','id'=>0];
            return $res;
        }
        $res = ['has_help_gift'=>0,'title'=>'','img'=>'','id'=>0,'other_name'=>$config['bargain_help_gift_other_name'],
            'other_phone'=>$config['bargain_help_gift_other_phone'],'bargain_help_gift_icon'=>$config['bargain_help_gift_icon']];
        $flag_num = self::checkUserHasHelpReceiveFlag($uid,$themeid);
        if ($flag_num>0){
            $item = self::getHelpReceiveFlagByUid($uid,$themeid);
            if ($item){
                $res['id'] = $item['hg_id'];
                $res['title'] = $item['g_name'];
                $res['img']=$item['g_img'];
                switch ($item['status']){
                    case 0:
                        $res['has_help_gift']=1;//选择礼品未填写信息
                        break;
                    case 1:
                        $res['has_help_gift']=2;//未核销
                        break;
                    case 2:
                        $res['has_help_gift']=3;//已核销
                        break;
                    default:
                        break;
                }
            }
        }
        return $res;
    }

    /**
     * Desc:判断用户是否存在帮砍奖品的记录
     * User:cbw
     * Time: 2021/2/23 3:08 下午
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function checkUserHasHelpReceiveFlag($uid,$themeid)
    {
        $sql = " select count(*) as cnt from".tablename(t_bargain_help_gift)." where themeid=$themeid and uid='{$uid}'";
        $res = db_find($sql)['cnt'];
        return $res;
    }

    /**
     * Desc:格式化助力礼品
     * User:cbw
     * Time: 2021/2/23 5:39 下午
     * @param $config
     * @return array
     */
    public static function formatHelpHasData($config)
    {
        $list = [];
        if ($config['bargain_help_gift_first']){
            if ($config['bargain_help_gift_first_name']){
                $title = $config['bargain_help_gift_first_name'];
            }else{
                $title = '礼品1';
            }
            $temp = ['img'=>$config['bargain_help_gift_first'],'title'=>$title,'id'=>1];
            array_push($list,$temp);
        }
        if ($config['bargain_help_gift_second']){
            if ($config['bargain_help_gift_second_name']){
                $title = $config['bargain_help_gift_second_name'];
            }else{
                $title = '礼品2';
            }
            $temp = ['img'=>$config['bargain_help_gift_second'],'title'=>$title,'id'=>2];
            array_push($list,$temp);
        }
        if ($config['bargain_help_gift_third']){
            if ($config['bargain_help_gift_third_name']){
                $title = $config['bargain_help_gift_third_name'];
            }else{
                $title = '礼品3';
            }
            $temp = ['img'=>$config['bargain_help_gift_third'],'title'=>$title,'id'=>3];
            array_push($list,$temp);
        }
        return $list;
    }

    public static function checkUserHasHelpBargainGiftInfo($uid,$themeid)
    {
        $status = 0;
        $item = self::checkUserHasHelpReceiveFlag($uid,$themeid);
        if ($item){
            if ($item['status']==0){
                $status=1;
            }elseif ($item['status']==1){
                $status=2;
            }elseif ($item['status']==2){
                $status=3;
            }
        }
    }

    /**
     * Desc:获取订单砍价实例数量 通过status
     * User: cbw
     * Time: 2020/12/5 2:37 下午
     * @param int $status 0 全部类型 1完成  2未完成   3已过期
     * @return mixed
     */
    public static function getBargainEntryCount($themeid,$status=0)
    {
        $condition = '';
        if ($status!=0){
            $condition = " and status=$status";
        }
        $sql = " select count(*) as cnt from ".tablename(t_bargain_entry)." where themeid=$themeid".$condition;

        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取当前已完成和进行中的砍价实例
     * User: cbw
     * Time: 2020/12/7 3:22 下午
     * @param $themeid
     * @return mixed
     */
    public static function getBargainEntryDefaultCount($themeid)
    {
        $sql = " select count(*) as cnt from ".tablename(t_bargain_entry)." where themeid=$themeid and status!=3";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取订单砍价实例的列表
     * User: cbw
     * Time: 2020/12/5 2:43 下午
     * @param int $status
     * @return mixed
     */
    public static function getBargainEntryListByStatus($themeid,$limit=12,$status=0)
    {
        $condition = "";
        if ($status!=0){
            $condition = " and a.status=$status";
        }
        $condition .= " limit $limit";
        $sql = " select a.*,b.avatar from ".tablename(t_bargain_entry)." as a left join " . tablename(t_fans). " as b on a.uid=b.uid".
            " where a.themeid=$themeid".$condition;
        return db_select($sql);
    }

    /**
     * Desc:获取正在抽奖的头像的砍价实例
     * User: cbw
     * Time: 2021/1/2 1:56 下午
     * @param $themeid
     * @param int $limit
     * @return mixed
     */
    public static function getBargainEntryUserIconList($themeid)
    {
        $sql = " select a.*,b.avatar from ".tablename(t_bargain_entry)." as a left join " . tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid
             where a.themeid=$themeid and a.status!=3 order by a.created_at desc limit 45";
        return db_select($sql);
    }

    /**
     * Desc:格式化在砍用户头像列表
     * User: cbw
     * Time: 2020/12/8 9:57 上午
     * @param $config
     * @param $themeid
     * @return array
     */
    public static function getRealAndVirtualInfo($config,$themeid)
    {
        $virtual_num = $config['fakejoin'];
        $real = self::getBargainEntryDefaultCount($themeid);

        $user_icon_list = [];
        $diff_icon_num = max(0,(45 - $real));
        if ($diff_icon_num>$virtual_num){
            $diff_icon_num = $virtual_num;
        }
        if ($real>0){
            $real_entry_list = self::getBargainEntryUserIconList($themeid);
            foreach ($real_entry_list as $k => $v){
                $temp = ['avatar'=>$v['avatar']];
                array_push($user_icon_list,$temp);
            }
        }
        if ($virtual_num>0 && $diff_icon_num>0){
            $virtual = self::getVirtualUser($diff_icon_num);
            foreach ($virtual as $key =>$val){
                $temp = ['avatar'=>$val['avatar']];
                array_push($user_icon_list,$temp);
            }
        }
        $user_icon_list = array_chunk($user_icon_list,9);
        return $user_icon_list;
    }

    /**
     * Desc:获取虚拟用户信息 指定的开始id和limit
     * User: cbw
     * Time: 2020/12/8 9:56 上午
     * @param $diff
     * @param $limit
     * @return mixed
     */
    public static function getVirtualUser($limit)
    {
        $diff = rand(1000,4200);
        $sql = "select * from ".tablename(t_2019fans)." where id>$diff limit $limit";
        return db_select($sql);
    }

    /**
     * Desc:插入订单砍价实例
     * User: cbw
     * Time: 2020/12/5 2:46 下午
     * @param $data
     * @return mixed
     */
    public static function insertBargainEntry($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(t_bargain_entry,$data);
        return $res;
    }

    /**
     * Desc:通过orderid 获取砍价实例
     * User: cbw
     * Time: 2020/12/7 11:00 上午
     * @param $order_id
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function checkBargainEntryByOrderId($order_id,$uid,$themeid)
    {
        if (empty($order_id)){
            $sql = "SELECT * FROM " . tablename ( t_bargain_entry ) . " 
                       WHERE uid = '{$uid}' and themeid={$themeid} ORDER BY created_at desc";
            $res = db_find($sql);
        }else{
            $res = db_get(t_bargain_entry,['order_id'=>$order_id,'uid'=>$uid,'themeid'=>$themeid]);
        }
        return $res;
    }

    public static function checkBargainEntryByOrderId2($order_id,$themeid)
    {
        $res = db_get(t_bargain_entry,['order_id'=>$order_id,'themeid'=>$themeid]);
        return $res;
    }
    /**
     * Desc:更新订单砍价实例
     * User: cbw
     * Time: 2020/12/5 2:51 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function updateBargainEntry($where,$data)
    {
        $res = db_update(t_bargain_entry,$data,$where);
        return $res;
    }

    /**
     * Desc:获取砍价实例的发起用户信息
     * User: cbw
     * Time: 2020/12/7 4:55 下午
     * @param $order_id
     * @return mixed
     */
    public static function getBargainEntryUserInfo($order_id)
    {
        $sql = " select a.uid,b.avatar,b.nickname,b.username from ".tablename(t_bargain_entry)." as a left join ".tablename(t_fans).
            " as b  on a.uid=b.uid where a.order_id=$order_id";
        return db_find($sql);
    }

    /**
     * Desc:获取帮砍列表 通过制定的条件  砍价id 发起用户uid
     * User: cbw
     * Time: 2020/12/5 3:14 下午
     * @param int $be_id
     * @param int $from_uid
     * @param int $page_index
     * @param int $page_size
     * @return mixed
     */
    public static function getBargainList($themeid,$be_id=0,$from_uid=0,$page_index=1,$page_size=10)
    {
        $where = " where themeid=$themeid and b_id >0";
        $default_condition = " order by created_at desc limit ".($page_index-1)*$page_size.','.$page_size;
        if ($be_id!=0){
            $where .= " and be_id=$be_id";
        }
        if ($from_uid!=0){
            $where .= " and from_uid='{$from_uid}'";
        }
        if ($be_id!=0 && $from_uid!=0){
            $where .= " and be_id=$be_id and from_uid='{$from_uid}'";
        }
        $sql = " select * from ".tablename(t_bargain_flag).$where.$default_condition;
        return db_find($sql);
    }

    /**
     * Desc:获取指定砍价实例的全部帮砍记录
     * User: cbw
     * Time: 2020/12/7 4:35 下午
     * @param int $be_id
     * @param int $from_uid
     * @return mixed
     */
    public static function getAllBargainList($themeid,$be_id=0,$from_uid=0)
    {
        $sql = " select * from ".tablename(t_bargain_flag)." where themeid=$themeid and be_id=$be_id  and uid!='{$from_uid}' and from_uid='{$from_uid}' order by created_at desc";
        return db_select($sql);
    }

    /**
     * Desc:获取包含自己的昂砍记录
     * User: cbw
     * Time: 2020/12/31 1:06 下午
     * @param $themeid
     * @param int $be_id
     * @param int $from_uid
     * @return mixed
     */
    public static function getAllBargainInSelfList($themeid,$be_id=0,$from_uid=0)
    {
        $sql = " select * from ".tablename(t_bargain_flag)." where themeid=$themeid and be_id=$be_id  and from_uid='{$from_uid}' order by created_at desc";
        return db_select($sql);
    }

    /**
     * Desc: 插入砍价助力信息
     * User: cbw
     * Time: 2020/12/5 6:41 下午
     * @param $data
     * @return mixed
     */
    public static function insertBargain($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(t_bargain_flag,$data);
        return $res;
    }

    /**
     * Desc:获取当前发起人的助力次数
     * User: cbw
     * Time: 2020/12/5 7:21 下午
     * @param $be_id
     * @param $from_uid
     * @return mixed
     */
    public static function getBargainCountByFromUidAndBeId($themeid,$be_id,$from_uid)
    {
        $sql = " select count(*) as cnt from ". tablename(t_bargain_flag) ." where themeid=$themeid and be_id=$be_id and from_uid='{$from_uid}'";

        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取帮砍记录数 不包含自身的砍价
     * User: cbw
     * Time: 2020/12/8 11:02 上午
     * @param $be_id
     * @param $from_uid
     * @param string $help_type
     * @return mixed
     */
    public static function getFriendBargainCountByFromUidAndBeId($themeid,$be_id,$from_uid,$help_type='friend')
    {
        if ($help_type!=='all'){
            $help_type = "and help_type='" .$help_type ."'";
        }else{
            $help_type = "";
        }
        $sql = " select count(*) as cnt from ". tablename(t_bargain_flag) ." where themeid=$themeid and be_id=$be_id ". $help_type ." and from_uid='{$from_uid}'";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取当前活动的帮砍总数
     * User: cbw
     * Time: 2020/12/10 11:01 上午
     * @param $themeid
     * @param string $help_type
     * @return mixed
     */
    public static function getFriendFlagByThemeid($themeid,$help_type='friend')
    {
        $sql = " select count(*) as cnt from ". tablename(t_bargain_flag) ." where themeid=$themeid and help_type='"."$help_type'";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:检查砍价状态 status 1正常 2拼团未开启 3活动未开始 4活动已结束 5砍价时间已到 过期 6砍价已完成
     * User: cbw
     * Time: 2020/12/5 3:38 下午
     * @param $system
     * @param $config
     * @param $theme
     * @param $bargainEntry
     * @return int
     */
    public static function checkBargainStatus($system, $theme, $config,$bargainEntry)
    {
        $status = 1;
        $now_time = time();
        if ($system['ruanjian']!=5){
            $status =2;
        }
        if ($theme['begintime']>$now_time){
            $status = 3;
        }
        if ($now_time>$theme['endtime']){
            $status = 4;
        }
        if (($bargainEntry['status']==2 && strtotime($bargainEntry['end_time'])<$now_time) || $bargainEntry['status']==3){
            $status = 5;
            if ($bargainEntry['status']==2 && strtotime($bargainEntry['end_time'])<$now_time){
                $where = ['be_id'=>$bargainEntry['be_id']];
                $data = ['status'=>3];
                $res = self::updateBargainEntry($where,$data);
                Sms::CheckAndSendSms('bargain_fail',$system,$config,$theme['id'], $bargainEntry);

                //砍价失败自动退款
                if ($config['bargain_mode']==1){
                    $theme['refundfee']=10000;
                    Record::refund($bargainEntry['order_id'],$bargainEntry['themeid'],$theme,$system,$config,'bargain_auto_refund');
                }
            }
        }
        if ($bargainEntry['status']==1){
           $status = 6;
        }
        return $status;
    }

    /**
     * Desc:获取非法砍价状态对应的返回信息
     * User: cbw
     * Time: 2020/12/7 11:36 上午
     * @param $status
     * @return array
     */
    public static function formatBargainStatus($status)
    {
        $modelshow = modelShow(40000);
        switch ($status){
            case 2:
                $modelshow = modelShow(40063);
                break;
            case 3:
                $modelshow = modelShow(40064);
                break;
            case 4:
                $modelshow = modelShow(40065);
                break;
            case 5:
                $modelshow = modelShow(40066);
                break;
            case 6:
                $modelshow = modelShow(40067);
                break;
            default:
                break;
        }
        return $modelshow;
    }

    /**
     * Desc:判断当前助力人是否存在指定砍价的助力记录
     * User: cbw
     * Time: 2020/12/5 3:56 下午
     * @param $uid
     * @return mixed
     */
    public static function checkUserHasBargainFlag($themeid,$uid,$order_id)
    {
        $res = db_get(t_bargain_flag,['themeid'=>$themeid,'uid'=>$uid,'order_id'=>$order_id]);
        return $res;
    }

    /**
     * Desc:获取当前助力人的总助力次数
     * User: cbw
     * Time: 2020/12/7 11:45 上午
     * @param $uid
     * @return mixed
     */
    public static function getUserBargainNum($themeid,$uid)
    {
        $sql = " select count(*) as cnt from".tablename(t_bargain_flag)." where themeid=$themeid and uid='{$uid}'";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取助力人的好友的总助力次数
     * User: cbw
     * Time: 2021/1/3 10:23 上午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getUserBargainFriendNum($themeid,$uid)
    {
        $sql = " select count(*) as cnt from".tablename(t_bargain_flag)." where themeid=$themeid and uid='{$uid}' and help_type='friend'";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取随机砍价金额
     * User: cbw
     * Time: 2020/12/5 9:13 下午
     * @param $fans
     * @param $from_uid
     * @param $type
     * @param $config
     * @return false|mixed|string
     */
    public static function getUserUsedAmount($system,$themeid,$fans,$from_uid,$order_id,$type,$config,$op_type='friend',$b_id=0)
    {
        $get_rand_float = false;
        try {
            $limit_price = $config['bargain_minprice'];//系统设定最低价
            //获取砍价实例
            $bargain_entry = self::getUserLastBargainEntry($themeid,$from_uid,$order_id);
            $remain_amount = $bargain_entry['remain_amount'];//当前砍至金额
            $data = [
                'uid'=>$fans['uid'],
                'avatar'=>$fans['avatar'],
                'order_id'=>$bargain_entry['order_id'],
                'be_id'=>$bargain_entry['be_id'],
                'from_uid'=>$from_uid,
                'help_type'=>$op_type,
                'themeid'=>$themeid
            ];
            $entry_where = ['be_id'=>$bargain_entry['be_id']];

            if ($type=='limit_user'){
                $bargain_limit = $config['bargain_friendnum'];//后台设定的砍价团人数
                $flag = self::getBargainCountByFromUidAndBeId($themeid,$bargain_entry['be_id'],$from_uid);

                if ($flag+1>=$bargain_limit){
                    //最后一次
                    $get_rand_float = $data['sub_amount']=number_format(($remain_amount-$limit_price), 2, '.', '');
                    $entry_data = [
                        'remain_amount'=>$limit_price,
                        'status'=>1
                    ];
                }else{
                    //后台设定的随机概率的值
                    $set_ratio = $config['bargain_pricerange'];
                    $diff_amount = $remain_amount-$limit_price;
                    $diff_num = $bargain_limit-$flag;
                    $diff_item_amount = (float)($diff_amount/$diff_num);
                    $min_ratio_amount = (100 - $set_ratio)/100*$diff_item_amount;
                    $max_ratio_amount = (100 + $set_ratio)/100*$diff_item_amount;
                    //限定的砍价人数
                    $get_rand_float = self::randomFloat($min_ratio_amount,$max_ratio_amount);
                    if ($op_type=='system'){
                        $get_rand_float = $max_ratio_amount;
                    }

                    if ($op_type=='share_double'){
                        $flag = self::getBargainFlagByBId($themeid,$b_id);
                        $flag_sub_amount = $flag['sub_amount'];
                        $get_rand_float = $flag_sub_amount;
                    }
                    $data['sub_amount']=$get_rand_float;
                    $entry_data = [
                        'remain_amount'=>$remain_amount-$get_rand_float
                    ];
                }

            }

            if ($type=='auto'){
                $rule_prices = $config['bargain_rules'];
                $get_rand_float = self::formatRulePrices($remain_amount,$rule_prices);
                //判断是否砍价完成
                if ($remain_amount-$get_rand_float>$limit_price){
                    if ($op_type=='system'){
                        $get_rand_float++;
                    }
                    if ($op_type=='share_double'){
                        $flag = self::getBargainFlagByBId($themeid,$b_id);
                        $flag_sub_amount = $flag['sub_amount'];
                        $get_rand_float = $flag_sub_amount;
                    }
                    $data['sub_amount'] = $get_rand_float;
                    $entry_data = [
                        'remain_amount'=>$remain_amount-$get_rand_float
                    ];
                }else{
                    //最后一次砍价完成
                    $data['sub_amount']=$remain_amount-$limit_price;
                    $entry_data = [
                        'remain_amount'=>$limit_price,
                        'status'=>1
                    ];
                    $get_rand_float = $remain_amount-$limit_price;
                }
            }
            if ( $entry_data['status']==1){
                Sms::CheckAndSendSms('bargain_success',$system,$config,$themeid, $bargain_entry,$data);
            }else{
                Sms::CheckAndSendSms('bargain_help',$system,$config,$themeid, $bargain_entry,$data);
            }
            //插入砍价记录
            $res = self::insertBargain($data);
            $b_id =  $insertid;
            //更新砍价实体
            $res_entry = self::updateBargainEntry($entry_where,$entry_data);
            return ['get_rand_float'=>$get_rand_float,'b_id'=>$b_id];
        }catch (Exception $e){
            return  $e->getMessage();
        }

    }

    /**
     * Desc:判断是否有对应类型的砍价记录
     * User: cbw
     * Time: 2020/12/7 9:22 下午
     * @param $order_id
     * @param $themeid
     * @param $uid
     * @param string $help_type system share share_double
     * @return mixed
     */
    public static function hasTypeFlag($themeid,$order_id,$uid,$help_type='system')
    {
        $sql = " select * from ".tablename(t_bargain_flag)." where themeid=$themeid and order_id=$order_id and help_type='".$help_type."' and uid='{$uid}'";
        return db_find($sql);
    }

    /**
     * Desc:获取用户最后一条 对应状态的 砍价实例
     * User: cbw
     * Time: 2020/12/5 4:33 下午
     * @param $uid
     * @return mixed
     */
    public static function getUserLastBargainEntry($themeid,$uid,$order_id,$status=0)
    {
        $condition = "";
        if ($status!=0){
            $condition = " and status=$status";
        }
        if (empty($order_id)){
            $sql = " select * from ".tablename(t_bargain_entry)." where uid='{$uid}' $condition and themeid=$themeid order by created_at  limit 1";
        }else{
            $sql = " select * from ".tablename(t_bargain_entry)." where uid='{$uid}' $condition and themeid=$themeid and order_id=$order_id order by created_at  limit 1";
        }
        return db_find($sql);
    }

    /**
     * Desc:获取用户最后一条进行中的砍价记录
     * User: cbw
     * Time: 2020/12/14 3:24 下午
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function getUserProcessBargainEntry($themeid,$uid,$status=3)
    {
        $sql = " select * from ".tablename(t_bargain_entry)." where uid='{$uid}' and status!=$status and themeid=$themeid order by created_at limit 1";
        return db_find($sql);
    }

    /**
     * Desc:获取用户对应状态的最新的一条砍价实例
     * User: cbw
     * Time: 2020/12/22 3:47 下午
     * @param $themeid
     * @param $uid
     * @param $status
     * @return mixed
     */
    public static function getUserBargainEntryByStatus($themeid,$uid,$status){
        $sql = " select * from ".tablename(t_bargain_entry)." where uid='{$uid}' and status=$status and themeid=$themeid order by created_at limit 1";
        return db_find($sql);
    }

    /**
     * Desc:根据后台阶梯价 获取当亲的随机砍价金额
     * User: cbw
     * Time: 2020/12/5 7:00 下午
     * @param $remain_amount
     * @param $rule_prices
     * @return string
     */
    public static function formatRulePrices($remain_amount,$rule_prices)
    {
        $temp_item = [];
        foreach ($rule_prices as $k =>$v)
        {
            if ($remain_amount>$v['rule_price']){
                $temp_item['rule_start'] = $v['rule_start'];
                $temp_item['rule_end'] = $v['rule_end'];
            }
        }
        $rand_float = self::randomFloat($temp_item['rule_start'],$temp_item['rule_end']);
        return $rand_float;
    }

    /**
     * Desc:生产保留两位小数的随机数
     * User: cbw
     * Time: 2020/12/5 5:32 下午
     * @param int $min
     * @param int $max
     * @return string
     */
    public static function randomFloat($min = 0, $max = 1)
    {
        $rand_float =  $min + mt_rand() / mt_getrandmax() * ($max - $min);
        return sprintf("%.2f",substr(sprintf("%.3f", $rand_float), 0, -2));
    }

    /**
     * Desc:获取砍价方式
     * User: cbw
     * Time: 2020/12/7 1:05 下午
     * @param $config
     * @return string
     */
    public static function getBargainType($config)
    {
        $type = 'limit_user';
        if (empty($config['bargain_friendnum']) && empty($config['bargain_pricerange'])){
            $type = 'auto';
        }
        return $type;
    }

    /**
     * Desc:获取活动的状态
     * User: cbw
     * Time: 2020/12/7 3:26 下午
     * @param $theme
     * @return int
     */
    public static function checkTheme($system,$theme)
    {
        $status = 1;
        $now_time = time();
        if ($system['ruanjian']!=5){
            $status =2;
        }
        if ($theme['begintime']>$now_time){
            $status = 3;
        }
        if ($now_time>$theme['endtime']){
            $status = 4;
        }
        return $status;
    }

    /**
     * Desc:默认代开的砍价提示语
     * User: cbw
     * Time: 2020/12/7 3:48 下午
     * @param $config
     * @param $flag
     * @return string
     */
    public static function getBargainTips($config,$flag)
    {
        $tips = '';
        $type = self::getBargainType($config);
        if ($type=='limit_user'){
            $remain = $config['bargain_friendnum'];
            if ($flag){
                $remain = max(1,($config['bargain_friendnum']-$flag));
            }
            $tips = '再邀请'.$remain.'人，即可砍价成功！';
        }
        if ($type=='auto'){
            $tips = '还差#DIJIA元即可砍价成功！';
        }
        return $tips;
    }

    /**
     * Desc:获取指定id的砍价记录
     * User: cbw
     * Time: 2020/12/7 9:49 下午
     * @param $b_id
     * @return mixed
     */
    public static function getBargainFlagByBId($themeid,$b_id)
    {
        $res = db_get(t_bargain_flag,['themeid'=>$themeid,'b_id'=>$b_id]);
        return $res;
    }

    /**
     * Desc:获取宝刀的提示语
     * User: cbw
     * Time: 2020/12/8 11:40 上午
     * @param $config
     * @return string
     */
    public static function getShopGridTips($theme)
    {
        $shop_name = substr($theme['jubf'],0,48);
        return '由'.$shop_name.'馈赠';
    }

    /**
     * Desc:获取用户指定订单的帮砍记录
     * User: cbw
     * Time: 2020/12/10 4:59 下午
     * @param $order_id
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function getUserBargainFlagList($order_id,$uid,$themeid)
    {
        $sql = "select a.*,b.username,b.nickname from ".tablename(t_bargain_flag)." as a left join ".tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid".
            " where a.order_id=$order_id and a.from_uid='{$uid}' and a.themeid=$themeid order by a.created_at desc";
        return db_select($sql);
    }

    /**
     * Desc:获取用户指定订单的帮砍记录不包含分享的
     * User: cbw
     * Time: 2020/12/22 8:21 下午
     * @param $order_id
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function getUserNotShareBargainFlagList($order_id,$uid,$themeid)
    {
        $sql = "select a.*,b.username,b.nickname from ".tablename(t_bargain_flag)." as a left join ".tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid".
            " where a.order_id=$order_id and a.from_uid='{$uid}' and a.themeid=$themeid  order by a.created_at desc";
        return db_select($sql);
    }

    /**
     * Desc:总计获取20条记录
     * User: cbw
     * Time: 2021/1/3 11:52 上午
     * @param $themeid
     * @param int $limit
     * @return mixed
     */
    public static function getAllBargainFlagListLimit($config,$themeid,$limit=20)
    {
        $sql = "select a.*,b.username,b.nickname from ".tablename(t_bargain_flag)." as a left join ".tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid".
            " where a.themeid=$themeid and a.help_type!='share' order by a.created_at desc limit $limit ";
        $list = db_select($sql);
        $xunilist=array();
        //如果砍价记录不够则取虚拟数
        if (count($list)<$limit && ($config['fakejoin']>0 || $config['faketuan']>0) ){
            $sql = "select avg(sub_amount) from ".tablename(t_bargain_flag)." as a 
                 where a.themeid=$themeid and a.help_type!='share' order by a.created_at asc limit 5 ";
            $amount_avg = db_fetchcolumn($sql);
            if (empty($amount_avg) && $config['bargain_friendnum']){
                $amount_avg=($config['bargain_marketprice']-$config['bargain_minprice'])/$config['bargain_friendnum'];
            }
            if (!empty($amount_avg)){
                if (strstr($config['softtag0'],"婚纱")!==false ){
                    $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+1045;
                }else{
                    $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+2545;
                }
                $tempcount = $limit-count($list);
                $xunisql = "SELECT id,username,nickname,avatar FROM " . tablename(t_2019fans) . " where
                         id >". $kaishishu ." limit ".$tempcount;
                $xunilist = db_select ( $xunisql );

                foreach ($xunilist as $index => $item){
                    if (empty($config['bargain_pricerange'])){
                        $pricerange = 1;
                    }else{
                        $nickname = mb_substr($item['nickname'],0,1,'utf-8');
                        //获取昵称的首字母取随机范围2倍的余数；
                        $nickname = mb_convert_encoding($nickname, 'GBK');
                        $pricerange = ord($nickname) % (intval($config['bargain_pricerange'])*2);
                        $pricerange  = 100-$config['bargain_pricerange'] + $pricerange;
                        $pricerange = $pricerange / 100;
                    }
                    $sub_amount = $amount_avg * $pricerange;
                    $xunilist[$index]['sub_amount']= round($sub_amount, 2);
                    if ($item['id'] % 11 ==0 && $config['bargain_self_grid']==1){
                        $xunilist[$index]['help_type']='system';
                    }elseif ($item['id'] % 11 ==9 && $config['bargain_self_dshare']==1){
                        $xunilist[$index]['help_type']='system';
                    }elseif ($item['id'] % 11 ==2 && $config['bargain_self_dshare']==1){
                        $xunilist[$index]['help_type']='share_double';
                    }elseif ($item['id'] % 11 ==7 && $config['bargain_self_dshare']==1){
                        $xunilist[$index]['help_type']='share_double';
                    }else{
                        $xunilist[$index]['help_type']='friend';
                    }
                }
            }
        }
        return array_merge($list , $xunilist);
    }
    /**
     * Desc:获取当前活动的砍价排行榜 砍价金额倒序  时间倒序
     * User: cbw
     * Time: 2020/12/10 5:03 下午
     * @param $themeid
     * @return mixed
     */
    public static function getBargainRanking($config,$themeid,$limit=20)
    {
        $sql = " select a.*,b.avatar,b.username,b.nickname from ".tablename(t_bargain_entry)." as a left join".tablename(t_fans)
            ." as b on a.uid=b.uid where a.themeid=$themeid group by a.uid order by a.remain_amount asc , a.created_at desc limit " . $limit;
        $list = db_select($sql);
        $xunilist=array();

        //判断多产品砍价
        $min_price_arr = [];
        if ($config['bargain_products'] && is_array($config['bargain_products'])){
            foreach ($config['bargain_products'] as $k => $v){
                if ($v['status']!=1 && !empty($v['name']) ){
                    $min_price_arr[] = $v['minprice'];
                }
            }
        }else{
            $min_price_arr[] = $config['bargain_minprice'];
        }
        //判断多产品砍价

        //如果砍价记录不够则取虚拟数
        if (count($list)<$limit && $config['fakejoin']>0 ) {
            if (strstr($config['softtag0'],"婚纱")!==false ){
                $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+1045+10*date('H');
            }else{
                $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+2545+10*date('H');
            }

            $tempcount = $limit-count($list);
            if ($tempcount>$config['fakejoin']){
                $tempcount = $config['fakejoin'];
            }
            $xunisql = "SELECT id,username,nickname,avatar FROM " . tablename(t_2019fans) . " where
                         id >". $kaishishu ." limit ".$tempcount;
            $xunilist = db_select ( $xunisql );

            foreach ($xunilist as $index => $item){
                //取昵称中的第一位根据ascii码算得秒数
                $nickname = mb_substr($item['nickname'],0,1,'utf-8');
                $nickname = mb_convert_encoding($nickname, 'GBK');
                $miao = ord($nickname) % 60;

                //取昵称中的第一位根据ascii码算得分钟数
                $nickname = mb_substr($item['nickname'],1,1,'utf-8');
                $nickname = mb_convert_encoding($nickname, 'GBK');
                $fen = ord($nickname) % 60;

                //取当前时间计算小时数
                $xiaoshi = date('H')-7;
                if ($xiaoshi<0){
                    $created_at=date("Y-m-d",'-1 day');
                    $xiaoshi = 12;
                }else{
                    $created_at=date("Y-m-d");
                }
                $xiaoshi = $xiaoshi==0?7:ord($nickname) % $xiaoshi + 7;
                if ($xiaoshi<10){ $xiaoshi = "0".$xiaoshi;}
                if ($fen<10){ $fen = "0".$fen;}
                if ($miao<10){ $miao = "0".$miao;}
                $created_at = $created_at ." " .$xiaoshi .":".$fen.":".$miao;
                $xunilist[$index]['created_at'] = $created_at;
                $xunilist[$index]['remain_amount'] = $min_price_arr[array_rand($min_price_arr)];
            }
        }
        //合并数组并排序
        $hebing = array_merge($xunilist,$list);
        $hebing = Bargain::bubbleSort($hebing,'created_at');
        return $hebing;
    }

//    冒泡法排序(数组，排序关键字）
    public static function bubbleSort ($arr,$sorttxt) {
        if (!is_array($arr)) return false;
        $len = count($arr);
        if ($len <= 1) return $arr;    //控制需要处理冒泡次数
        for ($i=1; $i<$len; $i++) {        //控制数组需要比较冒泡次数
            for ($k=0; $k < $len-$i; $k++)  {
                if ($arr[$k][$sorttxt] < $arr[$k+1][$sorttxt]) {
                    $tmp = $arr[$k];
                    $arr[$k] = $arr[$k+1];
                    $arr[$k+1] = $tmp;
                }
            }
        }
        return $arr;
    }


    /**
     * Desc:获取当前主体的所有的砍价记录
     * User: cbw
     * Time: 2020/12/22 5:03 下午
     * @param $themeid
     * @return mixed
     */
    public static function getAllBargainFlagList($themeid)
    {
        $sql = "select a.*,b.username,b.nickname from ".tablename(t_bargain_flag)." as a left join ".tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid".
            " where a.themeid=$themeid order by a.created_at desc";
        return db_select($sql);
    }

    /**
     * Desc:查询被人砍价实例中的对应的砍价记录 宝刀、分享、翻倍
     * User: cbw
     * Time: 2020/12/30 4:22 下午
     * @param $themeid
     * @param $uid
     * @param $help_type
     * @param $order_id
     * @return mixed
     */
    public static function getOrderSelfFlag($themeid,$uid,$help_type,$order_id)
    {
        $sql = " select * from ".tablename(t_bargain_flag)." where uid='{$uid}' and themeid=$themeid and order_id=$order_id and help_type='" . $help_type . "' order by created_at desc limit 1";
        return db_find($sql);
    }

    /**
     * Desc:获取不包含分享群聊的砍价记录
     * User: cbw
     * Time: 2020/12/22 8:16 下午
     * @param $themeid
     * @return mixed
     */
    public static function getNotShareBargainFlagList($themeid)
    {
        $sql = "select a.*,b.username,b.nickname from ".tablename(t_bargain_flag)." as a left join ".tablename(t_fans)." as b on a.uid=b.uid".
            " where a.themeid=$themeid and a.help_type!='share' order by a.created_at desc";
        return db_select($sql);
    }




    public static function checkSetBargainParams($config)
    {
        $modelShow = true;
        if (empty($config['bargain_products'])){
            if (empty($config['bargain_marketprice']) || empty($config['bargain_minprice'])) {
                $modelShow = modelShow(40060);
            }
            if ($config['bargain_limitstatus'] == 1 && $config['bargain_limit'] == 0) {
                $modelShow = modelShow(40061);
            }
        }
        return $modelShow;
    }

    //获取用户进行中及完成的砍价实例数量，确认是否达到限额；
    public static function get_user_bargain_entry($config,$themeid){
        global $_G;
        if ($config['bargain_products_limit']==0){
            return true;
        }
        $total = (int)db_fetchcolumn(" select count(*) from ".tablename(t_bargain_entry)." 
            where uid='{$_G['member']['uid']}' and status < 3 and themeid=$themeid order by created_at desc limit 1");
        if ($total>=$config['bargain_products_limit']){
            return false;
        }else{
            return true;
        }
    }
    //获取产品信息
    public static function format_products($products,$themeid){
        global $_G;
        $stock_total=0;
        $show_my_bargain = false;
        if (!empty($products)){
            $pro1=array();$pro2=array();$pro3=array();$pro4=array();
            foreach ($products as $index=>$item){
                if ($item['marketprice']>100){
                    $item['marketprice']=str_replace('.00','',$item['marketprice']);
                }
                if ($item['minprice']>100) {
                    $item['minprice'] = str_replace('.00', '', $item['minprice']);
                }
                $item['order_id']=0;
                $entry = db_find(" select * from ".tablename(t_bargain_entry)." 
                    where uid='{$_G['member']['uid']}' and status < 3 and products_id='{$item['id']}' and themeid=$themeid order by created_at desc limit 1");
                if (empty($entry)){
                    if ($item['status']==0){
                        $item['tips']='砍这个';
                        $pro1[]=$item;
                    }else{
                        $item['tips']='已抢光';
                        $pro4[]=$item;
                    }
                }else{
                    if (!empty($entry['order_id'])){
                        $themyorder = Order::getPayOrderByRIdZhifude($entry['order_id']);
                        if (!empty($themyorder)) {
                            $item['order_id']=$entry['order_id'];
                        }
                    }
                    if ($entry['status']==1){
                        $item['tips']='已完成';
                        $pro2[]=$item;
                    }elseif ($entry['status']==2){
                        $item['tips']='砍价中';
                        $pro3[]=$item;
                    }
                }

                $stock_total +=$item['stock'];
            }
            $products=array_merge($pro2,$pro3,$pro1,$pro4);

//            是否显示我的砍价
            $success_sql = " select * from ".tablename(t_bargain_entry)." 
            where uid='{$_G['member']['uid']}' and status='1' and themeid={$themeid} order by created_at desc limit 1";
            $success_item =  db_find($success_sql);
            if ($success_item){
                $show_my_bargain = true;
            }
        }

        return array('products'=>$products,'stock_total'=>$stock_total,'show_my_bargain'=>$show_my_bargain);
    }
    //获取产品信息
    public static function format_bargain_config($config,$products_id){
        if (!empty($config['bargain_products']) && !empty($products_id)){
            $products = $config['bargain_products'][$products_id-1];
            if (!empty($config['bargain_products'])) {
                $config['bargain_marketprice'] = $products['marketprice'];
                $config['bargain_minprice'] = $products['minprice'];
                $config['bargain_joinprice'] = $products['joinprice'];
                $config['bargain_limit'] = $products['stock'];
                $config['bargain_friendnum'] = $products['friendnum'];
                $config['bargain_products_name'] = $products['name'];
                $config['bargain_products_detail'] = $products['detail'];
                $config['bargain_products_img'] = $products['img'];
            }
        }
        return $config;
    }
    /**
     * Desc:api调用创建砍价实例
     * User: cbw
     * Time: 2020/12/11 1:59 下午
     * @param $themeid
     * @param $uid
     * @param $order_id
     * @return array|bool
     */
    public static function apiCreateBargain($theme,$config,$themeid,$uid,$order_id,$system)
    {
        $response = modelShow(40000);
        try {

            $record = Record::getById($order_id);
            $config = Bargain::format_bargain_config($config,$record['products_id']);
            $set_check = Bargain::checkSetBargainParams($config);//检测后天砍价设置
            if ($set_check!=true){
                return $set_check;
            }

            $sql = " select count(*) as cnt from ".tablename(t_bargain_entry)." where themeid=$themeid and order_id=$order_id";
            $check =db_find($sql)['cnt'];

            if ($check>0){
                return ;
                //订单存在
            }
            //无时间限制 存在未过期砍价实例,
            if (!$config['bargain_limittime']){
                if (empty($config['bargain_products'])){
                    $has_entry = Bargain::getUserCanUsedBargainEntry($themeid,$uid);
                    if ($has_entry && $has_entry['status']!=3){
                        return (array('errcode'=>1,'msg'=>'您有砍价进行中，不可发起新的砍价！'));
                    }
                }elseif (!empty($record['products_id'])){
//                    如果当前商品存在砍价，则只能发一起个砍价
                    $process_sql = " select * from ".tablename(t_bargain_entry)." where uid='{$uid}' and status =2 and themeid=$themeid order by created_at desc limit 1";
                    $process_item =  db_find($process_sql);
                    if ($process_item ){
                        return (array('errcode'=>1,'msg'=>'您有砍价进行中，不可发起新的砍价！'));
                    }
                    $process_sql = " select * from ".tablename(t_bargain_entry)." where uid='{$uid}' and status < 3 and products_id='{$record['products_id']}' and themeid=$themeid order by created_at desc limit 1";
                    $process_item =  db_find($process_sql);
                    if ($process_item ){
                        return (array('errcode'=>1,'msg'=>'此产品您只能发起一次砍价！'));
                    }
                }
            }
            //判断砍价进行时长
            if ($config['bargain_limittime']!=0){
                $time_type= 'limit';
                $end_time = date("Y-m-d H:i:s",strtotime("+".$config['bargain_limittime']." hours"));
            }else{
                $time_type= 'no_limit';
                $end_time = date("Y-m-d H:i:s",$theme['endtime']);
            }
            $remain_amount = $config['bargain_marketprice'];
            $show_grid = $config['bargain_self_grid']==1?'no':'no_show';//后台未设置宝刀开启
            $show_share = $config['bargain_self_share']==1?'no':'no_show';//后台未设置分享砍一刀
            $show_share_double = $config['bargain_self_dshare']==1?'no':'no_show';//后台未设置分享砍价金额翻倍

            // 判断后台定制是否开启 close关闭 process进行中 success成功未兑换 receive成功已兑换
            $bargain_gift = 'close';
            $bargain_gift_remain_num = 0;
            if ($system['bargain_gift']==1){
                //宝刀修改为关闭状态
                $show_grid = 'no_show';
                $bargain_gift = 'process';//定制的邀请有礼状态
                $bargain_gift_remain_num = intval($config['bargain_gift_limit']);//剩余邀请人数
            }

            $data = [
                'order_id'=>$order_id,
                'products_id'=>$record['products_id'],
                'remain_amount'=>$remain_amount,
                'end_time'=>$end_time,
                'status'=>2,
                'time_type'=>$time_type,
                'uid'=>$uid,
                'show_grid'=>$show_grid,
                'show_share'=>$show_share,
                'show_share_double'=>$show_share_double,
                'themeid'=>$themeid,
                'bargain_gift'=>$bargain_gift,//定制邀请有礼 状态
                'bargain_gift_remain_num'=>$bargain_gift_remain_num,//定制邀请有礼的 剩余邀请人数
            ];
            $bargain_entry_item = Bargain::insertBargainEntry($data);
            if ($bargain_entry_item){
                
                $response =array('errcode'=>1,'msg'=>'报名成功！');
            }
        }catch (Exception $e){

        }
        return $response;
    }

    /**
     * Desc:获取砍价实例列表以及搜索砍价实例
     * User: cbw
     * Time: 2020/12/12 11:50 上午
     * @param $themeid
     * @param string $nickname
     * @param string $start_day
     * @param string $end_day
     * @param string $order_id
     * @param $page_start
     * @param $page_size
     * @return mixed
     */
    public static function getDefaultOrSearchBargainEntry($themeid,$nickname='',$start_day='',$end_day='',$order_id='',$status=0,$page_start,$page_size)
    {
        $first_condition = " where a.themeid=$themeid";
        if ($status!=0){
            $first_condition = " where a.themeid=$themeid and a.status=$status";
        }

        $last_condition = " order by  a.created_at desc limit ".$page_start.",".$page_size;
        $condition = "";
        if ($nickname){
            $condition .= "  and b.nickname like '".$nickname."' ";
        }
        if ($start_day && $end_day){
            $condition .= "  and a.created_at between '".date("Y-m-d H:i:s",$start_day)."' and '".date("Y-m-d H:i:s",$end_day)."' ";
        }
        if ($order_id){
            $condition .= "  and a.order_id='".$order_id."' ";
        }
        $sql = "select a.*,b.username,b.avatar,b.nickname,b.mobile  from ".tablename(t_bargain_entry).
            " as a  LEFT JOIN ". tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid ".$first_condition.$condition.$last_condition;
        $list = db_select($sql);
        $sql = "select count(*)  from ".tablename(t_bargain_entry).
            " as a  LEFT JOIN ". tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid ".$first_condition.$condition;
        $total = (int)db_fetchcolumn($sql);
        return array('list'=>$list,'total'=>$total);
    }

    /**
     * Desc:通过themeid获取砍价实例概述
     * Time: 2020/12/12 1:20 下午
     * @param $themeid
     * @return array[]
     */
    public static function getBargainStatusList($themeid)
    {
        $list1 = self::getBargainEntryCount($themeid);
        $list2 = self::getBargainEntryCount($themeid,2);
        $list3 = self::getBargainEntryCount($themeid,1);
        $list4 = self::getBargainEntryCount($themeid,3);
        return [
            ['title'=>'全部','total'=>$list1,'status'=>0],
            ['title'=>'进行中','total'=>$list2,'status'=>2],
            ['title'=>'已完成','total'=>$list3,'status'=>1],
            ['title'=>'已过期','total'=>$list4,'status'=>3],
        ];
    }

    /**
     * Desc:获取帮看记录
     * User: cbw
     * Time: 2020/12/12 2:04 下午
     * @param $themeid
     * @param $be_id
     * @param $page_start
     * @param $page_size
     * @return mixed
     */
    public static function getBargainFlagList($themeid,$be_id,$page_start,$page_size)
    {
        $first_condition = " where a.themeid=$themeid";
        if ($be_id){
            $first_condition .= " and a.be_id=$be_id";
        }
        $last_condition = " order by  a.created_at desc ";
        if ( $page_size){
            $last_condition.= " limit $page_start,$page_size";
        }
        $sql = "select a.*,b.username,b.nickname,b.mobile,c.avatar as entry_avatar,c.username as entry_username,c.nickname as entry_nickname,c.mobile as entry_mobile  from ".tablename(t_bargain_flag).
            " as a  LEFT JOIN ". tablename(t_fans)." as b on a.uid=b.uid and  a.themeid=b.themeid ".
            " LEFT JOIN ".tablename(t_fans)." as c on a.from_uid=c.uid and a.themeid=c.themeid".$first_condition.$last_condition;

        return db_select($sql);
    }

    /**
     * Desc:帮砍助力记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/8/23 9:23 上午
     * @param $themeid
     * @param string $search
     * @param string $start_day
     * @param string $end_day
     * @param $page_start
     * @param $page_size
     * @return mixed
     */
    public static function getBargainHelpFlagList($themeid,$search='',$start_day='',$end_day='',$page_start,$page_size)
    {
        $condition1 = " ";
        $condition = " where a.themeid=$themeid ";
        if ($search){
            $condition .= " and c.username like '".$search."'"." or c.mobile like '".$search."' ";
        }
        if ($start_day && $end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        if ($page_size){
            $condition1 = " limit ".$page_start.",".$page_size;
        }
        $sql = "select a.*,b.username,b.nickname,b.mobile,c.avatar as entry_avatar,c.username as entry_username,c.nickname as entry_nickname,c.mobile as entry_mobile from ".
            tablename(t_bargain_flag)." as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid and  a.themeid=b.themeid".
            " LEFT JOIN ".tablename(t_fans)." as c on a.from_uid=c.uid and a.themeid=c.themeid".$condition.
            " group by a.from_uid order by a.created_at desc  ".$condition1;
//        var_dump($sql);
        return db_select($sql);
    }

    /**
     * Desc:判断订单形式的访问orderid是否属于当前访问用户
     * User: cbw
     * Time: 2020/12/22 3:34 下午
     * @param $themeid
     * @param $uid
     * @param $order_id
     * @return mixed
     */
    public static function checkUserOrder($themeid,$uid,$order_id)
    {
        $res = db_get(t_bargain_entry,['themeid'=>$themeid,'uid'=>$uid,'order_id'=>$order_id]);
        return $res;
    }

    /**
     * Desc:判断用户抢购套餐是否支付 返回BOOLEAN
     */
    public static function checkUserBuy($themeid,$uid)
    {
        global $_G;
        if(empty($uid)){
            $uid = $_G['member']['uid'];
        }
        $sql = "SELECT * FROM " . tablename (t_record) . "
                    WHERE themeid =:themeid and (uid = :uid or uid_other =:uid) and status =1 and type=24 order by id desc limit 1";
        $record = db_find($sql, array(":themeid"=>$themeid,":uid"=>$uid));
        if (empty($record)){
            return false;
        }else{
            return true;
        }
    }

    /**
     * Desc:通过砍价实例获取订单号
     * User: cbw
     * Time: 2020/12/23 3:22 下午
     * @param $themeid
     * @param $uid
     * @return int|mixed
     */
    public static function getUserRecordid($themeid,$uid){
        $result = Bargain::getUserCanUsedBargainEntry($themeid,$uid);
        if(!empty($result)) {
            $recordid=$result['order_id'];
        }else{
            $recordid = 0;
        }
        return $recordid;
    }

    /**
     * Desc:获取用户的进行中、已完成、已过期的砍价实例  一次查询 存在结果返回
     * User: cbw
     * Time: 2020/12/22 5:01 下午
     * @param $themeid
     * @param $uid
     * @return array
     */
    public static function getUserCanUsedBargainEntry($themeid,$uid)
    {
        //砍价实例状态 1完成 2未完成 3已过期
        $return_item = [];
        if (empty($uid)){
            return $return_item;
        }
        $process_sql = " select * from ".tablename(t_bargain_entry)." where uid='{$uid}' and status='2' and themeid=$themeid order by created_at desc limit 1";
        $process_item =  db_find($process_sql);
        if ($process_item){
            $return_item =  $process_item;
        }else{
            $success_sql = " select * from ".tablename(t_bargain_entry)." where uid='{$uid}' and status='1' and themeid=$themeid order by created_at desc limit 1";
            $success_item =  db_find($success_sql);
            if ($success_item){
                $return_item =  $success_item;
            }else{
                $outime_sql = " select * from ".tablename(t_bargain_entry)." where uid='{$uid}' and status='3' and themeid=$themeid order by created_at desc limit 1";
                $outtime_item =  db_find($outime_sql);
                if ($outtime_item){
                    $return_item = $outtime_item;
                }
            }
        }
        return $return_item;
    }

    /**
     * Desc:格式化砍价记录
     * User: cbw
     * Time: 2020/12/22 5:51 下午
     * @param $list
     * @return mixed
     */
    public static function formatBargainOrderFlag($list)
    {
        $now_time = strtotime(date("Y-m-d H:i:s"));
        foreach ($list as $key => $val)
        {
            foreach ($val as $k =>$v){
                if ($now_time-strtotime($v['created_at'])<3600){
                    $list[$key][$k]['in_one_hour'] = true;
                }else{
                    $list[$key][$k]['in_one_hour'] = false;
                }
            }

        }
        return $list;
    }

    /**
     * Desc: 检查用户砍价实例的礼物状态
     * User: cbw
     * Time: 2020/12/23 3:50 下午
     * @param $themeid
     * @param $order_id
     */
    public static function checkBargainEntryGift($themeid,$order_id)
    {
        $res = db_get(t_bargain_entry,['order_id'=>$order_id,'themeid'=>$themeid]);

        $where = ['order_id'=>$order_id,'themeid'=>$themeid];

        if ($res['bargain_gift']=='process'){
            $new_bargain_gift_remain_num = $res['bargain_gift_remain_num']-1;
            if ($new_bargain_gift_remain_num<=0){
                //邀请好友有礼完成
                $new_bargain_gift_remain_num = max(0,$new_bargain_gift_remain_num);

                $data = [
                    'bargain_gift_remain_num'=>$new_bargain_gift_remain_num,
                    'bargain_gift'=>'success'
                ];
            }else{
                //扣除1次人数
                $new_bargain_gift_remain_num = max(0,$new_bargain_gift_remain_num);

                $data = [
                    'bargain_gift_remain_num'=>$new_bargain_gift_remain_num
                ];
            }
            $update_res = self::updateBargainEntry($where,$data);
        }


    }

    /**
     * Desc:后台获取砍价状态数组
     * User: cbw
     * Time: 2020/12/24 10:36 上午
     * @param $themeid
     * @return array[]
     */
    public static function getAdminBargainStatusArr($themeid)
    {
        $list = [
            'all'=>self::getBargainEntryCount($themeid,0),
            'process'=>self::getBargainEntryCount($themeid,2),
            'success'=>self::getBargainEntryCount($themeid,1),
            'outtime'=>self::getBargainEntryCount($themeid,3)
        ];
        return $list;
    }

    /**
     * Desc:删除砍价实例
     * User: cbw
     * Time: 2020/12/24 11:15 下午
     * @param $themeid
     * @param $be_id
     * @return bool
     */
    public static function delBargainEntryByBeid($themeid,$be_id){
        $res = db_delete(t_bargain_entry,['themeid'=>$themeid,'be_id'=>$be_id]);
        if ($res){
            return true;
        }else{
            return false;
        }
    }

    /**
     * Desc:通过订单id 活动id删除用户的砍价实例
     * User:cbw
     * Time: 2021/2/27 7:56 下午
     * @param $themeid
     * @param $order_id
     * @return bool
     */
    public static function delUserBargainEntryFlagByOrderId($themeid,$order_id)
    {
        $res = db_delete(t_bargain_entry,['themeid'=>$themeid,'order_id'=>$order_id]);
        if ($res){
            return true;
        }else{
            return false;
        }
    }

    /**
     * Desc: 抽离获取砍价实例的攻略
     * User: cbw
     * Time: 2020/12/25 4:03 下午
     * @param $system
     * @param $config
     * @param $has_entry
     * @param $remain_entry_total
     * @param $option_status
     * @param $has_share
     */
    public static function getMethodList($system,$config,$has_entry,$remain_entry_total,$option_status,$has_share)
    {
        $method_list = [];
        //定制 判断砍价邀请好友有礼 判断是否支付

        $bargain_gift = [];
        $show_bargain_gift_modal = false;//判断是否在展示待兑换的模态框
        if ($system['bargain_gift']==1 && $has_entry['bargain_gift']!='close'){
            $limit = $has_entry['bargain_gift_remain_num'];
            $bargain_gift_status = $has_entry['bargain_gift'];
            $desc = '邀请'.$limit.'位好友帮砍，即可领取'.$config['bargain_gift_name'];
            if ($bargain_gift_status=='process' && $limit>0){
                $desc = '邀请'.$limit.'位好友帮砍，即可领取'.$config['bargain_gift_name'];
            }elseif ($bargain_gift_status=='success' && $limit==0){
                $desc = '邀请好友帮砍完成,'.'立即领取'.$config['bargain_gift_name'];
            }elseif ($bargain_gift_status=='receive' && $limit==0){
                $desc = '礼品领取成功，请到店核销兑换';
            }elseif ($bargain_gift_status=='verification'){
                $desc ='礼品已核销兑换';
            }

            $grid_item = ['title'=>'砍价邀请好友有礼','img'=>'https://css2020.yixuan.net/2020css/bargain/images/g3.png','status'=>2,
                'btnTxt'=>'去完成','desc'=>$desc,'b_id'=>0,'op_type'=>'bargain_gift','item_code'=>$has_entry['bargain_gift']];
            if ($remain_entry_total>0){
                if ($has_entry['bargain_gift']=='success'){
                    $grid_item['status']=1;
                    $grid_item['btnTxt']='待领取';
                    $show_bargain_gift_modal = true;
                }elseif ($has_entry['bargain_gift']=='receive'){
                    $grid_item['status']=1;
                    $grid_item['btnTxt']='已领取';
                }else{
                    if ($option_status=='out_time'){
                        $grid_item['status']=1;
                        $grid_item['btnTxt']='砍价失效';
                    }
                }
            }else{
                if ($has_entry['bargain_gift']=='success'){
                    $grid_item['status']=1;
                    $grid_item['btnTxt']='待领取';
                    $show_bargain_gift_modal = true;
                }elseif ($has_entry['bargain_gift']=='receive'){
                    $grid_item['status']=1;
                    $grid_item['btnTxt']='已领取';
                }else{
                    $grid_item['status']=3;
                    $grid_item['btnTxt']='已抢空';
                }
            }
            array_push($method_list,$grid_item);
            $bargain_gift = [
                'bargain_gift_img'=>$config['bargain_gift_img'],
                'bargain_gift_limit'=>intval($limit),
                'bargain_gift_name'=>$config['bargain_gift_name'],
                'bargain_buy'=>$config['bargain_buy'],
                'bargain_buy_text'=>$config['bargain_buy_text'],
                'bargain_order_text'=>$config['bargain_order_text'],
                'desc'=>$desc
            ];
        }
        //黄金宝刀判断定制  定制中不管宝刀是否开启  均不启用
        if ($config['bargain_self_grid']==1 && $system['bargain_gift']!=1){
            $grid_item = ['title'=>'黄金宝刀','img'=>'https://css2020.yixuan.net/2020css/bargain/images/g1.png','status'=>2,'btnTxt'=>'去完成','desc'=>'使用黄金宝刀可随机大额砍一刀','b_id'=>0,
                'op_type'=>'system','item_code'=>''];
            if ($remain_entry_total>0){
                if ($has_entry['show_grid']=='no'){
                    if ($option_status=='success'){
                        $grid_item['status']=1;
                        $grid_item['btnTxt']='砍价完成';
                    }elseif ($option_status=='out_time'){
                        $grid_item['status']=1;
                        $grid_item['btnTxt']='砍价失效';
                    }
                }elseif ($has_entry['show_grid']=='yes'){
                    $grid_item['status']=1;
                    $grid_item['btnTxt']='已完成';
                }
            }else{
                $grid_item['status']=3;
                $grid_item['btnTxt']='已抢空';
            }

            array_push($method_list,$grid_item);
        }
        //分享砍一刀
        if ($config['bargain_self_share']==1){
            $grid_item = ['title'=>'分享微信群','img'=>'https://css2020.yixuan.net/2020css/bargain/images/g5.png','status'=>2,'btnTxt'=>'去完成','desc'=>'分享到微信群即可砍一刀','b_id'=>0,
                'op_type'=>'share','item_code'=>''];
            if ($remain_entry_total>0){
                if ($has_entry['show_share']=='no'){
                    if ($option_status=='success'){
                        $grid_item['status']=1;
                        $grid_item['btnTxt']='砍价完成';
                    }elseif ($option_status=='out_time'){
                        $grid_item['status']=1;
                        $grid_item['btnTxt']='砍价失效';
                    }
                }elseif ($has_entry['show_share']=='yes'){
                    $grid_item['status']=1;
                    $grid_item['btnTxt']='已完成';
                }
            }else{
                $grid_item['status']=3;
                $grid_item['btnTxt']='已抢空';
            }
            array_push($method_list,$grid_item);
        }
        //再次分享加倍
        if ($config['bargain_self_dshare']==1){
            if ($remain_entry_total>0){
                $grid_item = ['title'=>'砍价金额翻倍','img'=>'https://css2020.yixuan.net/2020css/bargain/images/g2.png','status'=>2,'btnTxt'=>'去完成','desc'=>'分享微信群后再分享1个新群砍价金额翻倍',
                    'b_id'=>$has_share['b_id'],'op_type'=>'share_double','item_code'=>''];
                if ($has_entry['show_share_double']=='no'){
                    if ($option_status=='success'){
                        $grid_item['status']=1;
                        $grid_item['btnTxt']='砍价完成';
                    }elseif ($option_status=='out_time'){
                        $grid_item['status']=1;
                        $grid_item['btnTxt']='砍价失效';
                    }
                }elseif ($has_entry['show_share_double']=='yes'){
                    $grid_item['status']=1;
                    $grid_item['btnTxt']='已完成';
                }
            }else{
                $grid_item['status']=3;
                $grid_item['btnTxt']='已抢空';
            }

            array_push($method_list,$grid_item);
        }
        //邀请好友
        $grid_item = ['title'=>'快速邀请好友进行砍价','img'=>'https://css2020.yixuan.net/2020css/bargain/images/g4.png','status'=>2,'btnTxt'=>'去完成',
            'desc'=>'分享给好友时可选择多选，一次邀请多位好友；也可保存海报分享到朋友圈；','b_id'=>0,'op_type'=>'','item_code'=>''];
        if ($remain_entry_total>0){
            if ($option_status=='success'){
                $grid_item['status']=1;
                $grid_item['btnTxt']='砍价完成';
            }elseif ($option_status=='out_time'){
                $grid_item['status']=1;
                $grid_item['btnTxt']='砍价失效';
            }
        }else{
            $grid_item['status']=3;
            $grid_item['btnTxt']='已抢空';
        }
        array_push($method_list,$grid_item);


        return ['method_list'=>$method_list,'bargain_gift'=>$bargain_gift,'show_bargain_gift_modal'=>$show_bargain_gift_modal];
    }

    /**
     * Desc:本人存在砍价实例
     * User: cbw
     * Time: 2020/12/25 4:47 下午
     * @param $themeid
     * @param $order_id
     * @param $uid
     * @param $has_entry
     * @param $system
     * @param $config
     * @param $check_entry_status
     * @param $remain_entry_total
     * @return array
     */
    public static function getOrderArr($themeid,$order_id,$uid,$has_entry,$system,$config,$check_entry_status,$remain_entry_total)
    {
        $order_id = $has_entry['order_id'];
        //进行中 判断宝刀、分享、翻倍是否存在记录 默认都是否
        $used_grid = $used_share = $used_share_double = false;
        $has_share = self::hasTypeFlag($themeid,$order_id,$uid,'share');
        if ($has_entry['status']==2){
            if ($has_entry['show_grid']=='no'){
                $used_grid = true;
            }
            if ($has_entry['show_share']=='no'){
                $used_share = true;
            }
            if ($has_entry['show_share_double']=='no'){
                $used_share_double = true;
            }
            if ($has_entry['show_share_double']=='no' && $has_entry['show_grid']=='no'){
                $used_share_double = false;
            }
        }
        //判断是否是定制 曦尊
        if ($system['bargain_gift']==1){
            $used_grid = false;
        }
        //获取帮砍记录
        $get_bargain_order_flag = self::getUserBargainFlagList($order_id,$uid,$themeid);

        //发起人的用户信息 头像 姓名 昵称
        $self_info = self::getBargainEntryUserInfo($order_id);
        $option_status = 'wait';//砍价进行中
        //砍价是否完成
        if ($check_entry_status==6){//砍价已完成
            $option_status = 'success';
        }
        if ($check_entry_status==5){//砍价时间到达
            $option_status = 'out_time';
        }
        //倒计时 时间戳
        $countdown = strtotime($has_entry['end_time']);
        //获取砍价实例的帮砍记录
        $bargain_flag_list = self::getAllBargainList($themeid,$has_entry['be_id'],$uid);
        //获取包含自己的帮砍记录
        $bargain_tips_flag_list = self::getAllBargainInSelfList($themeid,$has_entry['be_id'],$uid);
        if ($option_status=='wait'){
            $tips = self::getBargainTips($config,count($bargain_tips_flag_list));
        }elseif ($option_status=='success'){
            $tips = '恭喜您，砍价已完成';
        }elseif ($option_status=='out_time'){
            $tips = '重新发起砍价';
        }
        //获取砍价实例类型
        $type = self::getBargainType($config);
        if ($type=='limit_user'){

            $now_flag = self::getBargainCountByFromUidAndBeId($themeid,$has_entry['be_id'],$uid);
            $has_limit = true;
            $remain_num = max(0,($config['bargain_friendnum']-$now_flag));
        }else{
            $has_limit = false;
            $remain_num = '';
        }
        //判断当前定单是否支付
        $isorder = false;
        if(!empty($order_id)){
            $noworder=Record::getById($order_id);
            if ($noworder['status'] > 0 && $noworder['status']!=3){
                $isorder=true;
            }
        }
        if ($config['bargain_marketprice']-$config['bargain_minprice']>0){
            $runing = intval(($config['bargain_marketprice']-$has_entry['remain_amount'])/($config['bargain_marketprice']-$config['bargain_minprice'])*100);
        }else{
            $runing = 0;
        }

        //如果价格没有小数位则取整
        if($has_entry['remain_amount']*100==intval($has_entry['remain_amount'])*100){
            $has_entry['remain_amount']=intval($has_entry['remain_amount']);
        }
        if($config['bargain_minprice']*100==intval($config['bargain_minprice'])*100){
            $config['bargain_minprice']=intval($config['bargain_minprice']);
        }
//        $tips = str_replace("#DIJIA",$config['bargain_marketprice']-$has_entry['remain_amount'],$tips);
        $tips = str_replace("#DIJIA",$has_entry['remain_amount'],$tips);
        $get_method_arr = self::getMethodList($system,$config,$has_entry,$remain_entry_total,$option_status,$has_share);
        $order_bargain_info = [
            'bargain_flag_list'=>$bargain_flag_list,//砍价头像列表
            'bargain_flag_total'=>count($bargain_flag_list),//砍价人数
            'bargain_gift'=>$get_method_arr['bargain_gift'],//定制邀请获得好礼内容
            'bargain_gift_status'=>$has_entry['bargain_gift'],//定制邀请获得好礼内容
            'bargain_minprice'=>$config['bargain_minprice'],
            'countdown'=>$countdown,//倒计时
            'has_limit'=>$has_limit,//是否有剩余显示
            'isorder'=>$isorder,//是否支付
            'method_list'=>$get_method_arr['method_list'],
            'option_status'=>$option_status,//砍价进行状态 wait 进行中 success 砍价完成 out_time 砍价超时
            'order_id'=>$has_entry['order_id'],
            'remain_amount'=>$has_entry['remain_amount'],
            'remain_num'=>$remain_num,//剩余次数
            'runing'=>$runing,
            'self_info'=>$self_info,//发起人信息
            'show_bargain_gift_modal'=>$get_method_arr['show_bargain_gift_modal'],//判断好友是否待兑换邀请好友有礼的modal
            'tips'=>$tips
        ];

        return ['order_bargain_info'=>$order_bargain_info,'used_grid'=>$used_grid,
            'used_share'=>$used_share,'used_share_double'=>$used_share_double,'get_bargain_order_flag'=>$get_bargain_order_flag];
    }

    /**
     * Desc:获取基本信息
     * User: cbw
     * Time: 2020/12/25 5:07 下午
     * @param $config
     * @param $theme
     * @param $resal_theme_help_total
     * @param $success_total
     * @param $remain_entry_total
     * @param $mode
     * @param $is_new_order
     * @return array
     */
    public static function getDefaultArr($config,$theme,$resal_theme_help_total,$success_total,$remain_entry_total,$mode,$is_new_order)
    {
        global $_G;
        //参与人数
        $total1 = Record::getNumByThemeId($theme['id'],$config['touxiang'],$config['showalldata']);
        $totalsum = $total1 + $config['faketuan'];
        //首页基础信息
        $default_info = array(
            'bargain_marketprice'=>$config['bargain_marketprice'],//原价
            'bargain_minprice'=>$config['bargain_minprice'],//砍最低价
            'bargain_joinprice'=>$config['bargain_joinprice'],//定金
            'bargain_liucheng'=>$config['bargain_liucheng'],//流程图
            'bargain_yaoqing'=>$config['bargain_yaoqing'],//邀请图
            'bargain_unpaid_button'=>$config['bargain_unpaid_button'],//支付定金抢购文字：未付
            'bargain_paid_button'=>$config['bargain_paid_button'],//支付定金抢购文字：已付
            'title'=>$theme['title'],//主标题
            'desc'=>$theme['desc'],//副标题
            'help_total'=>$config['fakejoin']+$resal_theme_help_total,//帮砍人数
            'success_total'=>$success_total,
            'totalsum'=>$totalsum,
            'bargain_isdirectbuy'=>$config['bargain_isdirectbuy'],//直接原价购买 0关闭 1开启
            'bargain_mode'=>$config['bargain_mode'],//付款方式 0 先付款后砍价-不退款  1先付款后砍价-失败退 2砍至底价下单 3 砍价中随时下单
            'remain_entry_total'=>$remain_entry_total,
            'bargain_limittime'=>$config['bargain_limittime'],
            'mode'=>$mode,//模式 default默认 bargain_gift 曦尊定制
            'bargain_gift_img'=>$config['bargain_gift_img'],//邀请好友有礼：礼品图
            'is_new_order'=>$is_new_order,
            'bargain_buy_text'=>$config['bargain_buy_text'],
            'bargain_order_text'=>$config['bargain_order_text'],
            'bargain_buy'=>$config['bargain_buy'],
            'bargain_buy_show_money'=>$config['bargain_buy_show_money'],//定制   判断是否显示价格
            'bargain_help_info_tips'=>$config['bargain_help_info_tips'],
            'bargain_showinfojoin'=>$config['bargain_showinfojoin'],
            'products'=>$config['bargain_products'],
            'bargain_self_share'=>$config['bargain_self_share'],
            'products_new'=>Bargain::get_user_bargain_entry($config,$theme['id']),
        );
        $products = Bargain::format_products($default_info['products'],$theme['id']);
        $default_info['products'] =$products['products'];
        $default_info['stock_total'] =$products['stock_total'];
        $default_info['show_my_bargain'] =$products['show_my_bargain'];
        $default_info['bargain_products_name'] = $config['bargain_products_name'];
        $default_info['bargain_products_detail'] = $config['bargain_products_detail'];
        $default_info['bargain_products_img'] = $config['bargain_products_img'];
        //定制   判断是否强制收集信息
        if ($config['bargain_help_info']==1){
            $pm = array(":themeid"=>$theme['id'],":uid"=>$_G['member']['uid']);
            $fans = db_find("SELECT * FROM ".tablename(t_fans)."
                            WHERE themeid = :themeid and uid = :uid",$pm);
            if (!empty($fans['username']) && !empty($fans['mobile'])){
                $default_info['bargain_help_info'] = 0;
            }else{
                $default_info['bargain_help_info' ]= 1;
            }
        }
        return $default_info;
    }

    /**
     * Desc:获取好友帮砍到访的数据
     * User: cbw
     * Time: 2020/12/25 6:00 下午
     * @param $themeid
     * @param $uid
     * @param $from_uid
     * @param $order_id
     * @param $config
     * @param $check_entry_status
     * @param $has_entry
     * @param $tips
     * @return array
     */
    public static function getHelpArr($themeid,$uid,$from_uid,$order_id,$config,$check_entry_status,$has_entry)
    {
        //发起人的用户信息 头像 姓名 昵称
        $self_info = Bargain::getBargainEntryUserInfo($order_id);
        $option_status = 'wait';//砍价进行中
        //砍价是否完成
        if ($check_entry_status==6){//砍价已完成
            $option_status = 'success';
        }
        if ($check_entry_status==5){//砍价时间到达
            $option_status = 'out_time';
        }
        //倒计时 时间戳
        $countdown = strtotime($has_entry['end_time']);
        //获取砍价实例的帮砍记录
        $bargain_flag_list = Bargain::getAllBargainList($themeid,$has_entry['be_id'],$from_uid);
        //获取砍价实例
        $type = Bargain::getBargainType($config);
        if ($type=='limit_user'){

            $now_flag = Bargain::getBargainCountByFromUidAndBeId($themeid,$has_entry['be_id'],$from_uid);
            $has_limit = true;
            $remain_num = max(0,($config['bargain_friendnum']-$now_flag));
        }else{
            $has_limit = false;
            $remain_num = '';
        }
        //判断当前定单是否支付
        $isorder = false;
        if(!empty($order_id)){
            $noworder=Record::getById($order_id);
            if ($noworder['status'] > 0 && $noworder['status']!=3){
                $isorder=true;
            }
        }
        $runing = ($config['bargain_marketprice']-$config['bargain_minprice'])*100;
        if ($runing!=0){
            $runing =($config['bargain_marketprice']-$has_entry['remain_amount']) / $runing;
        }


        //如果价格没有小数位则取整
        if($has_entry['remain_amount']*100==intval($has_entry['remain_amount'])*100){
            $has_entry['remain_amount']=intval($has_entry['remain_amount']);
        }
        if($config['bargain_minprice']*100==intval($config['bargain_minprice'])*100){
            $config['bargain_minprice']=intval($config['bargain_minprice']);
        }
        $order_bargain_info = [
            'order_id'=>$has_entry['order_id'],
            'remain_amount'=>$has_entry['remain_amount'],
            'bargain_minprice'=>$config['bargain_minprice'],
            'bargain_flag_list'=>$bargain_flag_list,//砍价头像列表
            'bargain_flag_total'=>count($bargain_flag_list),//砍价人数
            'has_limit'=>$has_limit,//是否有剩余显示
            'remain_num'=>$remain_num,//剩余次数
            'isorder'=>$isorder,//是否支付
            'runing'=>$runing,
            'option_status'=>$option_status,//砍价进行状态 wait 进行中 success 砍价完成 out_time 砍价超时
            'self_info'=>$self_info,//发起人信息
            'countdown'=>$countdown,//倒计时
        ];
        //获取帮砍人记录
        $has_bargain_flag = Bargain::checkUserHasBargainFlag($themeid,$uid,$order_id);
        $help_bargain_info = $order_bargain_info;
        $help_bargain_info['is_help'] = $has_bargain_flag?true:false;
        $help_bargain_info['help_info']=$has_bargain_flag;
        //判断帮砍人是否存在进行中的砍价实例
        $help_friend_has_bargain = false;
        $help_friend_bargain = Bargain::getUserCanUsedBargainEntry($themeid,$uid);
        if ($help_friend_bargain){
            $help_friend_has_bargain = true;
        }
        $help_bargain_info['help_friend_has_bargain'] = $help_friend_has_bargain;
        $help_bargain_info['help_friend_bargain'] = $help_friend_bargain;
        return $help_bargain_info;
    }

    /**
     * Desc:非默认打开使用的获取帮看记录
     * User: cbw
     * Time: 2020/12/25 5:13 下午
     * @param $get_bargain_order_flag
     * @return mixed
     */
    public static function getFormatBargainOrderFlag($get_bargain_order_flag)
    {
        $bargain_order_flag = [];
        //获取帮砍记录
        if (count($get_bargain_order_flag)>0){
            $bargain_order_flag = formatSelfPointsFlag($get_bargain_order_flag);
        }
        $bargain_order_flag = Bargain::formatBargainOrderFlag($bargain_order_flag);
        return $bargain_order_flag;
    }

    /**
     * Desc:获取昂砍记录是第几次
     * User: cbw
     * Time: 2020/12/31 7:44 下午
     * @param $bid
     * @param $from_uid
     * @return mixed
     */
    public static function getCurrentFlagInAllFlag($bid,$from_uid)
    {
        $sql = "select b_id,(select count(*) from ".tablename(t_bargain_flag)." as a where a.from_uid=$from_uid) as cc from"
            .tablename(t_bargain_flag)." where b_id=$bid";
        $res = db_find($sql);
        return $res;
    }

    /**
     * Desc:获取订阅消息的数组
     * User: cbw
     * Time: 2020/12/31 7:46 下午
     * @return string[]
     */
    public static function getBargainWxSendTmpIds()
    {
        return ['ex6b8_460Zv5EhEvA8sluO27zjrqQOzFvbWDWU-InKo','RexX3JbTD-BRqoiZJImIO-PnO94cXBLUFvhNx-rO03o','-eYlHJBp7LHoyCr_oM_x88qusrSFOyPlkENLwt4xouA','45DthCZyHRzEgidHIg9zER42TOZSYJMYDD1PupYge9s'];
    }

    /**
     * Desc:通过用户uid获取用户的openid
     * User: cbw
     * Time: 2020/12/31 8:30 下午
     * @param $uid
     * @return mixed
     */
    public static function getUserOpenidByUid($uid)
    {
        $res = db_get(t_fans,['uid'=>$uid]);
        return $res;
    }
}